package common

import (
	"fmt"
	"github.com/BurntSushi/toml"
	"os"
)

var (
	config Config
)

type Config struct {
	Server *ServerConfig `toml:"server"`
	Mysql  *MysqlConfig  `toml:"mysql"`
	Redis  *RedisConfig  `toml:"redis"`
	Log    *LogConfig    `toml:"log"`
}

type RedisConfig struct {
	Host     string `toml:"host"`
	Port     int    `toml:"port"`
	Password string `toml:"password"`
	Db       int    `toml:"db"`
	// 池子大小
	PoolSize int `toml:"pool_size"`
	// 最小空闲连接数
	MinIdleConns int `toml:"min_idle_conns"`
	// 最大空闲连接数
	MaxIdleConns int `toml:"max_idle_conns"`
}

type LogConfig struct {
	Level         string `toml:"level"`
	FilePath      string `toml:"file_path"`
	FileName      string `toml:"file_name"`
	FileErrorName string `toml:"file_error_name"`
	Formatter     string `toml:"formatter"`
	MaxSizeMb     int    `toml:"max_size_mb"`
	MaxAgeDay     int    `toml:"max_age_day"`
	MaxBackups    int    `toml:"max_backups"`
	ShowFileLine  bool   `toml:"show_file_line"`
}

type ServerConfig struct {
	Host    string `toml:"host"`
	Port    int    `toml:"port"`
	Debug   bool   `toml:"debug"`
	PidFile string `toml:"pidfile"`
	GinMode string `toml:"ginMode"`
}

type MysqlConfig struct {
	Host         string `toml:"host"`
	Port         int    `toml:"port"`
	User         string `toml:"user"`
	Password     string `toml:"password"`
	DbName       string `toml:"db_name"`
	MaxOpenConns int    `toml:"max_open_conns"`
	MaxIdleConns int    `toml:"max_idle_conns"`
}

func InitConfig(configPath string) {
	// 初始化配置
	if _, err := toml.DecodeFile(configPath, &config); err != nil {
		fmt.Printf("fail to read config.||err=%v||config=%v", err, configPath)
		os.Exit(1)
	}
}

func GetConfig() *Config {
	return &config
}

// 初始化配置
func InitConfigForTest() {
	configPath := "../conf/service.conf"
	InitConfig(configPath)
}

// 初始化配置
func InitConfigForSecondDeepTest() {
	configPath := "../../conf/service.conf"
	InitConfig(configPath)
}
